package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AliPayService;
import com.atguigu.gmall.payment.service.PaymentService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author: 李旭
 * @create: 2021-09-14 14:21
 *
 *   支付宝管理
 *   #同步通知地址
 * return_payment_url=http://api.gmall.com/api/payment/alipay/callback/return
 * #异步通知地址
 * notify_payment_url=http://hkkgun.natappfree.cc/api/payment/alipay/callback/notify
 **/
@Controller
@RequestMapping("/api/payment/alipay")
public class AliPayController {

    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private PaymentService paymentService;

    //点击支付宝的扫码支付
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submitAliPay(@PathVariable Long orderId){
        return aliPayService.submitAliPay(orderId);
    }


    //同步通知请求
    @GetMapping("/callback/return")
    public String callbackReturn(){
        //商户的成功页面  重定向
        System.out.println("同步通知");
        return "redirect:" + AlipayConfig.return_order_url;
    }
    //异步通知请求
    @PostMapping("/callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){
        //将异步通知中收到的所有参数都存放到map中
        System.out.println(paramsMap);

        //{gmt_create=2021-09-15 10:15:36,
        // charset=utf-8,
        // gmt_payment=2021-09-15 10:15:43,
        // notify_time=2021-09-15 10:15:44,
        // subject=Apple iPhone 12 Pro Max (A2412) 256GB 海蓝色 支持移动联通电信5G 双卡双待手机 Apple iPhone 11 (A2223) 64GB 红色 移动联通电信4G,
        // sign=XvhjdkzE3Sw5c6bb5yno0yxx96mX1Q06LjZe1/rFqXG5oQURfLj6A0rJaxhgEpC0NicnuuZwtexuryK6QY7jG17oSh8STujbPWosRr/xHV/b58UP3G5xmc1NJTs6fdueYLSY0K4DmCVWA4Q+BLrUT58jbg3QV6itwxGMzpwsJeT0uIPMc15P137kX35r5+STyLRMVMqD+l5eRtKIWEc/Ni4MGm5Nn9NPQwUHIFQvWwEq9pqbnx/ovtofFC2MF9eT9qLFWnh12ymz36/Il8g2AKc67gbI/4JE0rwruOM1mFtjpi0AhTedhXQMPhN5ZQtDfKUcc5L65t2GAgfxFHfASw==,
        // buyer_id=2088102181130586,
        // body=Apple iPhone 12 Pro Max (A2412) 256GB 海蓝色 支持移动联通电信5G 双卡双待手机 Apple iPhone 11 (A2223) 64GB 红色 移动联通电信4G,
        // invoice_amount=57792.00,
        // version=1.0,
        // notify_id=2021091500222101543030580517434401,
        // fund_bill_list=[{"amount":"57792.00","fundChannel":"ALIPAYACCOUNT"}],
        // notify_type=trade_status_sync,
        // out_trade_no=ATGUIGU1631672105714318,
        // total_amount=57792.00,
        // trade_status=TRADE_SUCCESS,
        // trade_no=2021091522001430580501649117, auth_app_id=2016102100732915, receipt_amount=57792.00, point_amount=0.00, app_id=2016102100732915, buyer_pay_amount=57792.00, sign_type=RSA2, seller_id=2088102180533564}


        try {
            boolean rsaCheckV1 = AlipaySignature.
                    rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key,
                            AlipayConfig.charset,AlipayConfig.sign_type);
            if(rsaCheckV1){
                //验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                System.out.println("异步通知并验签成功");
                if("TRADE_SUCCESS".equals(paramsMap.get("trade_status"))){
                    //根据钱的金额进行二次校验  本项目不关心此事 就算了
                    PaymentInfo paymentInfo = paymentService.getPaymentInfo(paramsMap.get("out_trade_no"));
                    BigDecimal totalAmount = paymentInfo.getTotalAmount();
                    String total_amount = paramsMap.get("total_amount");
                    if(totalAmount.toString().equals(total_amount)){
                        //更新支付表
                        paymentService.updatePaymentInfo(paramsMap);
                        return "success";
                    }else{
                        //日志  支付宝那边收款的总金额不正确
                        return "failure";
                    }
                }else{
                    return "failure";
                }
            }else{
                //验签失败则记录异常日志，并在response中返回failure.
                System.out.println("异步通知并验签失败");
                //记录异常日志
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }

    //退款
    @GetMapping("/refund/{outTradeNo}")
    public Result refund(@PathVariable String outTradeNo){
        aliPayService.refund(outTradeNo);
        return Result.ok();
    }
}
